import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/cache/id_cache.dart';
import 'package:wu_you/data/repository/trad_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/trad_model.dart';
import 'package:wu_you/page/trad/page_order_detail.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/trad_bloc.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/http_list_widget.dart';
import 'package:wu_you/utils/extension_utils.dart';

///我的订单
class TradOrderPage extends StatefulWidget{
  final String name;
  TradOrderPage({Key key,this.name}):super(key: key);
  @override
  TradOrderPageState createState() => TradOrderPageState();
}
class TradOrderPageState extends State<TradOrderPage>{
  List<String> _tabs = [];
  @override
  void initState() {
    super.initState();
  }
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    _tabs.clear();
    _tabs = ['${message['trad58']}','${message['trad59']}','${message['trad60']}'];
    return DefaultTabController(
      length: _tabs.length,
      child:  Scaffold(
        appBar: AppBar(
          title: Text("${message['trad70']}"),
        ),
        backgroundColor: Colors.white,
        body: Column(
          children: [
            TabBar(
              labelColor: AppColors.primaryColor,
              indicatorColor: AppColors.primaryColor,
              unselectedLabelColor: AppColors.textColor,
              indicatorSize: TabBarIndicatorSize.label,
              // isScrollable: true,
              tabs: _tabs.map((e) => Tab(text: e,)).toList(),
            ),
            Expanded(
              child: TabBarView(
                physics: NeverScrollableScrollPhysics(), //禁止滑动
                children: [
                  _BottomListView(type: "1",name: widget.name,),
                  _BottomListView(type: "2",name: widget.name,),
                  _BottomListView(type: "3",name: widget.name,)
                ]
              )
            )
          ],
        ),
      )
    );
  }
}

class _BottomListView extends StatefulWidget{
  final String type;
  final String name;
  _BottomListView({Key key,this.type,this.name}):super(key: key);
  @override
  _BottomListViewState createState() => _BottomListViewState();
}
class _BottomListViewState extends State<_BottomListView>{

  String userId;
  @override
  void initState() {
    super.initState();
    _getUserId();
  }
  _getUserId(){
    UserIdCache().get().then((value){
      setState(() {
        userId = value;
      });
    });
  }
  BuildContext ctx;
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return HttpListWidget<MyAdOrders, MyAdListBloc>(
      creator: (context) => MyAdListBloc(),
      onObtainData: (context, page) {
        BlocProvider.of<MyAdListBloc>(context).add(MyAdListEvent(status: widget.type,page: page));
      },
      successBuilder: (context, data) {
        ctx = context;
        return ListView.builder(
          itemBuilder: (context,index){
            MyAdOrders item = data[index];
            Widget child;
            if(widget.type == "1"){
              child = Text("${message['trad51']}",style: TextStyle(color: AppColors.primaryColor),).addGesture(() {
                showCupertinoDialog(
                    context: context,
                    builder: (context) {
                      return CupertinoAlertDialog(
                        title: Text('${message['trad68']}'),
                        content: Text('${message['trad69']}'),
                        actions: <Widget>[
                          CupertinoDialogAction(child: Text('${message['address14']}'),onPressed: (){
                            Navigator.pop(context);
                          },),
                          CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: (){
                            LoadingApi.func(TradRepository().cancelMyAd(item.id), context,complete: (v){
                              ToastUtils.show("${message['Success']}", context);
                              Navigator.pop(context);
                              BlocProvider.of<MyAdListBloc>(ctx).add(MyAdListEvent(status: widget.type,page: 1));
                            },error: (e){
                              ToastUtils.show("$e", context);
                            });
                          },),
                        ],
                      );
                    });
              });
            }else{
              child = Text("${_showStatus(item.order_status ?? "")}${_showAppeal(item)}",style: TextStyle(color: _statusColor(item.order_status)),);
            }
            return Column(
              children: [
                Container(
                  decoration: new BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                    border: new Border.all(width: 1, color: HexColor("#F6F6F6")),
                  ),
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: 12,right: 12,bottom: 12,top: 6),
                  padding: EdgeInsets.all(15),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              // Image.network("${item.wid_logo}",width: 20,height: 20,),
                              // SizedBox(width: 3,),
                              Text("${item.wid_name}"),
                              SizedBox(width: 2,),
                              Text(_showOrderType(item),style: TextStyle(color: AppColors.secondColor),)
                            ],
                          ),
                          child
                        ],
                      ),
                      SizedBox(height: 6,),
                      Text("${message['trad52']}：${double.parse(item.quantity).toStringAsFixed(2)}"),
                      SizedBox(height: 6,),
                      Text("${widget.name == "MYR" ? 'MYR' : '¥'}${item.price}    ${message['trad53']}：${widget.name == "MYR" ? 'MYR' : '¥'}${item.total_price}"),
                      SizedBox(height: 6,),
                      Text("${message['trad54']}：${widget.type == "1" ? item.create_time : item.order_create_time}"),
                      SizedBox(height: 6,),
                      Offstage(
                        offstage: widget.type == "3" ? false : true,
                        child: Text("${message['trad55']}：${item.finnshed_time ?? 0}"),
                      )
                    ],
                  ),
                ).addGesture(() {
                  if(widget.type == "1"){
                    return;
                  }
                  NavigatorUtil.navigateToPage(context, OrderDetailPage(id: item.id)).then((value){
                    if(value != null){
                      BlocProvider.of<MyAdListBloc>(ctx).add(MyAdListEvent(status: widget.type,page: 1));
                    }
                  });
                }),
                Divider(thickness: 5,),

              ],
            );
          },
          itemCount: data.length
        );
      },
      emptyBuilder: (context){
        ctx = context;
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(Utils.getImgPath("ic_empty",), width: 60, fit: BoxFit.fitWidth,),
            SizedBox(height: 10,),
            Text("${message['noData']}", style: TextStyle(color: AppColors.textHintColor, fontSize: 14),),
          ],
        );
      },
    );
  }

  String _showOrderType(MyAdOrders model){
    // print("我的userId:${userId}");
    if(widget.type == "1" || userId == model.uid){
      if(model.type == "1"){
        return "(${message['trad47']})"; //卖单
      }else{
        return "(${message['trad48']})"; //买单
      }
    }else{
      if(model.type == "1"){
        return "(${message['trad48']})"; //买单
      }else{
        return "(${message['trad47']})"; //卖单
      }
    }
  }


  ///状态
  String _showStatus(String status){
    switch(status){
      case "0":
        return "${message['trad56']}"; //已取消
      case "10":
        return "${message['trad62']}"; //未付款
      case "20":
        return "${message['trad63']}"; //已付款
      case "30":
        return "${message['trad60']}"; //已完成
      default:
        return "";
    }
  }
  String _showAppeal(MyAdOrders item){
    if(item.appeal == "1"){
      return "(${message['trad66']})";  ///申诉中
    }else{
      if(item.pay_status == "2"){
        return "(${message['trad50']})"; ///已驳回凭证
      }else{
        return "";
      }
    }
  }

  Color _statusColor(String status){
    switch(status){
      case "0":
        return Colors.green;
      case "10":
        return HexColor("#ed1324");
      case "20":
        return AppColors.textHintColor;
      case "30":
        return HexColor("#38b640");
      default:
        return Colors.black;
    }
  }
}